<template>
  <view class="search-result">
    <!-- 导航栏 -->
    <NavBar :title="`搜索：${keyword}`" />

    <!-- 搜索栏 -->
    <view class="search-bar">
      <nut-searchbar 
        v-model="searchValue" 
        placeholder="搜索商品" 
        @search="onSearch"
        @clear="clearSearch"
      />
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view 
        class="filter-item" 
        :class="{ active: sortBy === 'default' }"
        @click="changeSort('default')"
      >
        <text>综合</text>
      </view>
      <view 
        class="filter-item" 
        :class="{ active: sortBy === 'sales' }"
        @click="changeSort('sales')"
      >
        <text>销量</text>
      </view>
      <view 
        class="filter-item" 
        :class="{ active: sortBy === 'price' }"
        @click="changeSort('price')"
      >
        <text>价格</text>
        <view class="sort-icon">
          <ArrowUp size="12" :color="sortOrder === 'asc' && sortBy === 'price' ? '#fa2c19' : '#999'" />
          <ArrowDown size="12" :color="sortOrder === 'desc' && sortBy === 'price' ? '#fa2c19' : '#999'" />
        </view>
      </view>
      <view 
        class="filter-item" 
        @click="showFilterPopup = true"
      >
        <text>筛选</text>
        <Category size="14" />
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <!-- 空结果提示 -->
      <nut-empty v-if="goodsList.length === 0 && !loading" description="暂无相关商品" image="search">
        <template #footer>
          <nut-button type="primary" size="small" @click="goHome">去首页</nut-button>
        </template>
      </nut-empty>

      <!-- 商品列表 -->
      <view v-else class="goods-grid">
        <view 
          class="goods-item" 
          v-for="(item, index) in goodsList" 
          :key="index"
          @click="goToGoodsDetail(item.id)"
        >
          <image :src="item.imgUrl" class="goods-image" mode="aspectFill" />
          <view class="goods-info">
            <view class="goods-name">{{ item.name }}</view>
            <view class="goods-price">
              <nut-price :price="item.price" size="normal" />
              <text class="goods-sales">已售{{ item.sales || 0 }}件</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="goodsList.length > 0 && !loading" class="load-more">
        <view v-if="hasMore" class="loading" @click="loadMore">
          <Loading size="16px" /> 加载中...
        </view>
        <view v-else class="no-more">没有更多了</view>
      </view>
    </view>

    <!-- 加载中 -->
    <view class="loading-container" v-if="loading">
      <Loading type="spinner" size="24px" />
      <text>加载中...</text>
    </view>

    <!-- 筛选弹出层 -->
    <nut-popup position="right" v-model:visible="showFilterPopup" :style="{ width: '80%', height: '100%' }">
      <view class="filter-popup">
        <view class="filter-header">
          <text class="title">商品筛选</text>
          <Close @click="showFilterPopup = false" />
        </view>
        
        <view class="filter-content">
          <!-- 价格区间 -->
          <view class="filter-section">
            <view class="section-title">价格区间</view>
            <view class="price-range">
              <nut-input-number v-model="minPrice" min="0" placeholder="最低价" />
              <text class="separator">-</text>
              <nut-input-number v-model="maxPrice" min="0" placeholder="最高价" />
            </view>
          </view>
          
          <!-- 分类 -->
          <view class="filter-section">
            <view class="section-title">商品分类</view>
            <view class="category-list">
              <nut-checkbox-group v-model="selectedCategories">
                <nut-checkbox 
                  v-for="(category, index) in categories" 
                  :key="index"
                  :label="category.id"
                >
                  {{ category.name }}
                </nut-checkbox>
              </nut-checkbox-group>
            </view>
          </view>
          
          <!-- 品牌 -->
          <view class="filter-section">
            <view class="section-title">品牌</view>
            <view class="brand-list">
              <nut-checkbox-group v-model="selectedBrands">
                <nut-checkbox 
                  v-for="(brand, index) in brands" 
                  :key="index"
                  :label="brand.id"
                >
                  {{ brand.name }}
                </nut-checkbox>
              </nut-checkbox-group>
            </view>
          </view>
        </view>
        
        <view class="filter-footer">
          <nut-button type="default" @click="resetFilter">重置</nut-button>
          <nut-button type="primary" @click="applyFilter">确定</nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import { ArrowUp, ArrowDown, Category, Close, Loading } from '@nutui/icons-vue-taro'
import NavBar from '@/components/NavBar/index.vue'
import goodsApi from '@/api/goods'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const keyword = router?.params?.keyword || ''

// 搜索相关
const searchValue = ref(keyword)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

// 排序筛选
const sortBy = ref('default') // default, sales, price
const sortOrder = ref('desc') // asc, desc
const showFilterPopup = ref(false)

// 价格筛选
const minPrice = ref('')
const maxPrice = ref('')

// 分类筛选
const categories = ref([
  { id: '1', name: '手机' },
  { id: '2', name: '电脑' },
  { id: '3', name: '平板' },
  { id: '4', name: '耳机' },
  { id: '5', name: '智能手表' },
  { id: '6', name: '相机' }
])
const selectedCategories = ref([])

// 品牌筛选
const brands = ref([
  { id: '1', name: '苹果' },
  { id: '2', name: '华为' },
  { id: '3', name: '小米' },
  { id: '4', name: '三星' },
  { id: '5', name: 'OPPO' },
  { id: '6', name: 'vivo' }
])
const selectedBrands = ref([])

// 商品列表
const goodsList = ref([])

// 搜索商品
const searchGoods = async (isLoadMore = false) => {
  if (!searchValue.value.trim()) {
    goodsList.value = []
    return
  }
  
  loading.value = true
  
  try {
    // 构建查询参数
    const params = {
      keyword: searchValue.value,
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value !== 'default' ? sortBy.value : undefined,
      sortOrder: sortOrder.value,
      minPrice: minPrice.value ? Number(minPrice.value) : undefined,
      maxPrice: maxPrice.value ? Number(maxPrice.value) : undefined,
      categoryIds: selectedCategories.value.length > 0 ? selectedCategories.value.join(',') : undefined,
      brandIds: selectedBrands.value.length > 0 ? selectedBrands.value.join(',') : undefined
    }
    
    // 实际项目中应该调用API搜索商品
    // const res = await goodsApi.searchGoods(params)
    // if (isLoadMore) {
    //   goodsList.value = [...goodsList.value, ...res.data.list]
    // } else {
    //   goodsList.value = res.data.list
    // }
    // hasMore.value = goodsList.value.length < res.data.total
    
    // 模拟数据
    setTimeout(() => {
      const mockData = [
        {
          id: '1',
          name: 'iPhone 13 Pro Max',
          price: '8999',
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/223778/18/6959/103158/61cc7965E6f1e0dda/a4a0450759d5614e.jpg',
          sales: 1000
        },
        {
          id: '2',
          name: '华为 Mate 50 Pro',
          price: '6999',
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/106207/35/33316/168578/632a7361E7bd1f38e/1006e302770e3811.jpg',
          sales: 800
        },
        {
          id: '3',
          name: '小米 12S Ultra',
          price: '5999',
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/178015/17/30654/74077/6368cb89Ef2f24f3d/a6c2443c9e2ce491.jpg',
          sales: 600
        },
        {
          id: '4',
          name: 'OPPO Find X5 Pro',
          price: '5499',
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/195164/25/30800/47837/635f8075E27fad736/6c86f44d0f9aa3c3.jpg',
          sales: 500
        }
      ]
      
      if (isLoadMore) {
        goodsList.value = [...goodsList.value, ...mockData]
      } else {
        goodsList.value = mockData
      }
      
      hasMore.value = currentPage.value < 3 // 模拟只有3页数据
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('搜索商品失败', error)
    Taro.showToast({
      title: '搜索失败',
      icon: 'none'
    })
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  currentPage.value++
  searchGoods(true)
}

// 搜索
const onSearch = (val) => {
  searchValue.value = val
  currentPage.value = 1
  searchGoods()
  
  // 保存搜索历史
  saveSearchHistory(val)
}

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  if (!keyword.trim()) return
  
  let history = Taro.getStorageSync('searchHistory')
  let historyList = history ? JSON.parse(history) : []
  
  // 如果已存在，先移除
  const index = historyList.findIndex(item => item === keyword)
  if (index !== -1) {
    historyList.splice(index, 1)
  }
  
  // 添加到最前面
  historyList.unshift(keyword)
  
  // 最多保存10条
  if (historyList.length > 10) {
    historyList = historyList.slice(0, 10)
  }
  
  // 保存到本地
  Taro.setStorageSync('searchHistory', JSON.stringify(historyList))
}

// 清空搜索
const clearSearch = () => {
  searchValue.value = ''
  goodsList.value = []
}

// 改变排序方式
const changeSort = (type) => {
  if (type === 'price') {
    // 价格排序特殊处理，点击切换升降序
    if (sortBy.value === 'price') {
      sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
    } else {
      sortBy.value = 'price'
      sortOrder.value = 'asc'
    }
  } else {
    sortBy.value = type
    sortOrder.value = 'desc'
  }
  
  currentPage.value = 1
  searchGoods()
}

// 重置筛选
const resetFilter = () => {
  minPrice.value = ''
  maxPrice.value = ''
  selectedCategories.value = []
  selectedBrands.value = []
}

// 应用筛选
const applyFilter = () => {
  currentPage.value = 1
  searchGoods()
  showFilterPopup.value = false
}

// 跳转到商品详情
const goToGoodsDetail = (id) => {
  Taro.navigateTo({
    url: `/pages/goods-details/index?id=${id}`
  })
}

// 跳转到首页
const goHome = () => {
  Taro.switchTab({
    url: '/pages/index/index'
  })
}

// 监听搜索值变化
watch(searchValue, (newVal) => {
  if (!newVal.trim()) {
    goodsList.value = []
  }
})

// 页面加载时执行
onMounted(() => {
  if (searchValue.value) {
    searchGoods()
  }
})
</script>

<style lang="scss">
.search-result {
  min-height: 100vh;
  background-color: #f7f8fa;
  
  .search-bar {
    background-color: #fff;
    padding: 8px 16px;
    position: sticky;
    top: 0;
    z-index: 10;
  }
  
  .filter-bar {
    display: flex;
    background-color: #fff;
    padding: 10px 0;
    margin-bottom: 10px;
    position: sticky;
    top: 56px;
    z-index: 10;
    
    .filter-item {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #333;
      position: relative;
      
      &.active {
        color: #fa2c19;
        font-weight: 500;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -10px;
          left: 50%;
          transform: translateX(-50%);
          width: 20px;
          height: 2px;
          background-color: #fa2c19;
          border-radius: 2px;
        }
      }
      
      .sort-icon {
        display: flex;
        flex-direction: column;
        margin-left: 4px;
        line-height: 1;
      }
    }
  }
  
  .goods-list {
    padding: 0 10px;
    
    .goods-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
      margin-bottom: 10px;
    }
    
    .goods-item {
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      
      .goods-image {
        width: 100%;
        height: 0;
        padding-bottom: 100%;
        position: relative;
        background-color: #f5f5f5;
      }
      
      .goods-info {
        padding: 8px;
        
        .goods-name {
          font-size: 14px;
          color: #333;
          margin-bottom: 6px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          line-height: 1.3;
          height: 36px;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-sales {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .load-more {
      text-align: center;
      padding: 15px 0;
      color: #999;
      font-size: 14px;
      
      .loading {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      
      .no-more {
        color: #999;
      }
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 30px 0;
    color: #999;
    font-size: 14px;
    
    text {
      margin-top: 10px;
    }
  }
  
  .filter-popup {
    display: flex;
    flex-direction: column;
    height: 100%;
    
    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #f5f5f5;
      
      .title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .filter-content {
      flex: 1;
      overflow-y: auto;
      padding: 15px;
    }
    
    .filter-section {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        font-size: 15px;
        font-weight: 500;
        margin-bottom: 10px;
      }
    }
    
    .price-range {
      display: flex;
      align-items: center;
      
      .separator {
        margin: 0 10px;
      }
    }
    
    .category-list,
    .brand-list {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
    }
    
    .filter-footer {
      display: flex;
      padding: 15px;
      border-top: 1px solid #f5f5f5;
      
      .nut-button {
        flex: 1;
        margin: 0 5px;
      }
    }
  }
}
</style>